package com.yupi.springbootinit.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

/**
 * @Description
 * @Author minify
 * @Date 2023/12/19 21:14
 * @Project mybi-backend
 */
public class DirectProducer {

    private static final String EXCHANGE_NAME = "direct_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置RabbitMQ相关信息
        factory.setHost("localhost");
        // 创建一个新的连接
        Connection connection = factory.newConnection();
        // 创建一个通道
        Channel channel = connection.createChannel();
        // 声明一个交换机
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        // 发送消息到交换机
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String input = scanner.next();
            String[] split = input.split(",");
            String routingKey = split[0];
            String message = split[1];
            channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8"));
            System.out.println("Producer Send +'" + message + "'" + " routingKey:" + routingKey);
        }
        // 关闭资源
        channel.close();
        connection.close();
    }
}
